import { Toast } from 'vant'

const FileUtils = {
  async downloadFile (data) {
    Toast.loading({
      duration: 0,
      message: '正在下载文件...',
      forbidClick: true,
      overlay: true
    })
    if (Object.prototype.toString.call(data).slice(8, -1) !== 'Object') {
      throw new Error('param of data must be a object')
    }
    const { name, url } = data
    var _this = this
    console.log('name', name)
    console.log('url', url)
    console.log('window.requestFileSystem====>', window.requestFileSystem)
    try {
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
        function (fileSystem) {
          console.log('fileSystem====>', fileSystem)
          fileSystem.root.getDirectory('tw_check_documents', {
            create: true
          }, function (dirEntry) {
            console.log('dirEntry====>', dirEntry)
            dirEntry.getFile(name, {
              create: true
            }, function (fileEntry) {
              _this._download(fileEntry, url)
            }, function (err) {
              Toast.clear()
              console.log('errorinner')
              console.log(err)
            })
          }, function (err) {
            Toast.clear()
            console.log('erroroutter')
            console.log(err)
          })
        })
    } catch (err) {
      console.log(err)
      Toast.clear()
    }
  },
  _download (fileEntry, url) {
    console.log('url', url)
    const uri = encodeURI(url)
    console.log('uri', uri)
    console.log('开始下载')
    console.log(fileEntry, url)
    const fileTransfer = new FileTransfer()
    console.log('查看fileTransfer', fileTransfer)
    const fileUrl = fileEntry.toURL()
    console.log('查看fileUrl', fileUrl)
    fileTransfer.download(
      uri,
      fileUrl,
      function (entry) {
        Toast('下载成功:文件保存于/本地/内部存储/tw_check_documents')
        console.log('下载成功')
        console.log('文件保存位置:' + entry.toURL())
      },
      function (error) {
        Toast.clear()
        Toast('下载失败！')
        console.log('download error')
        console.log(error)
      }
    )
  },
  checkFileExist (data) {
    if (Object.prototype.toString.call(data).slice(8, -1) !== 'Object') {
      throw new Error('param of data must be a object')
    }
    const { name, url } = data
    console.log('name', name)
    console.log('url', url)
    console.log('window.requestFileSystem====>', window.requestFileSystem)
    return new Promise((resolve, reject) => {
      try {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
          function (fileSystem) {
            console.log('fileSystem====>', fileSystem)
            fileSystem.root.getDirectory('tw_check_documents', {
              create: true
            }, function (dirEntry) {
              var dirReader = dirEntry.createReader()
              dirReader.readEntries(function (results) {
                console.log(JSON.stringify(results))
                let flag = false
                for (var i = 0; i < results.length; i++) {
                  if (results[i].isFile && results[i].name == name) {
                    flag = true
                  }
                }
                resolve(flag)
              })
            }, function (err) {
              Toast.clear()
              reject(false)
              console.log('erroroutter')
              console.log(err)
            })
          })
      } catch (err) {
        Toast.clear()
        reject(false)
        console.log(err)
      }
    })
  },
  /**
   * 在手机根目录下创建文件夹
   * @param {Object} directoryPath 全路径
   * @param {Object} success
   * @param {Object} fail
   */
  createFloderMethod: function (directoryPath, success, fail) {
    var createDir = function (rootDir, folders) {
      if (folders.length === 0) {
        success(rootDir)
        return
      }
      rootDir.getDirectory(folders[0], {
        create: true,
        exclusive: false
      }, function (dirEntry) {
        if (folders.length) {
          createDir(dirEntry, folders.slice(1))
        }
      }, fail)
    }
    var getFileSystemSuccess = function (fileSystem) {
      // createDir(fileSystem.root, directoryPath.split('/'))
      var folders = directoryPath.split('/').filter(function(folder) { if (folder != "") {return true}})
			createDir(fileSystem.root, folders);

    }
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, getFileSystemSuccess, fail)
  },
  /**
   * @description: 在浏览器根目录下创建文件夹
   * @param {*} directoryPath 全路径
   * @param {*} success
   * @param {*} fail
   * @return {*}
   */  
  createFloderPCMethod:function(directoryPath, success, fail){
    function createDir(rootDir, folders) {
      if(folders.length == 0){
        success(rootDir);
        return;
      }
      rootDir.getDirectory(folders[0], {
        create: true,
        exclusive: false
      }, function(dirEntry) {
        if (folders.length) {
          createDir(dirEntry, folders.slice(1));
        }
      }, fail);
    };
    function initFS(fs) {
      createDir(fs.root, directoryPath.split('/'));
    }
    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(window.TEMPORARY, 50 *1024* 1024, initFS, fail);
  },
  /**
  * @description: 打开文件
  * @param {*} name 文件名称
  * @return {*}
  */
  openFile(name) {
    //判断文件是否存在
    //filePath 文件路径  路径+文件名
    // 相对路径和绝对路径都可
    let self = this
    let path="/storage/emulated/0/tw_check_documents/"+name;
    console.log(path)
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
      //查询获得文件目录
      fileSystem.root.getDirectory("/storage/emulated/0/tw_check_documents/", {
            create: false,
            exclusive: false
          },
          function(dirEntry) {
            var dirReader = dirEntry.createReader();
            dirReader.readEntries(function(results) {
              var callbackContext = {}
              callbackContext.success = function(obj) {
                console.log("apk文件打开成功回调:" + obj)
              }
              callbackContext.error = function(err) {
                console.log("apk文件打开失败回调:" + JSON.stringify(err))
              }
              deliver.openFile(callbackContext.success, callbackContext.error,[path])
              console.log("245文件存在")
            }, function() {
              console.log("248内容不存在")
            });
          },
          function() {
            console.log("251文件不存在")
            var callbackContext = {}
            callbackContext.success = function(obj) {
              console.log("apk文件打开成功回调:" + obj)
            }
            callbackContext.error = function(err) {
              console.log("apk文件打开失败回调:" + JSON.stringify(err))
            }
            deliver.openFile(callbackContext.success, callbackContext.error,[path])
            console.log("目录不存在")
          });
    }, function() {
        console.log("255文件不存在")
    });
  },
}

export default FileUtils
